from django.conf import settings
from django.utils import translation
from django.http import HttpResponseRedirect, Http404
import re

class DifferentLanguageMiddleware:
    def process_request(self, request):
        rules = settings.DIFFERENT_LANGUAGE
        for pattern, lang in rules:
            if re.compile(pattern).match(request.path):
                translation.activate(lang)
                # TODO check cookie/session 'django_language'
                # request.LANGUAGE_CODE = translation.get_language()
                return

class ForceExpireSessionMiddleware:
    def process_request(self, request):
        try:
            pattern = settings.FORCE_EXPIRE_SESSION_FOR_URLS
        except:
            return
        if re.compile(pattern).match(request.path):
            settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True
            settings.SESSION_SAVE_EVERY_REQUEST = True

class CascadeRedirectIf404Middleware:
    def process_exception(self, request, exception):
        if isinstance(exception, Http404) and len(request.path) > 1:
            return HttpResponseRedirect(request.path.rstrip('/').rsplit('/', 1)[0] + '/')
